package com.sweet.encrypt;

import com.sweet.enums.Charset;

import java.security.MessageDigest;

/**
 * MD5工具类
 */
public final class MD5 {
	private final static String TYPE = "MD5";

	/** 默认UTF-8编码 */
	private final static Charset CHARSET = Charset.UTF8;

	/** 定义加密后要显示的字符 */
	private static char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	private MD5() {
	}

	/**
	 * 获取16位加密算法
	 * 
	 * @param data
	 * @return
	 */
	public static String get16MD5(String data) {
		return get16MD5(data, CHARSET);
	}

	/**
	 * 获取32位加密算法
	 * 
	 * @param data
	 * @return
	 */
	public static String get32MD5(String data) {
		return get32MD5(data, CHARSET);
	}

	/**
	 * 获取16位加密算法
	 * 
	 * @param data
	 * @param charset
	 * @return
	 */
	public static String get16MD5(String data, Charset charset) {
		return encrypt(data, charset).substring(8, 24);
	}

	/**
	 * 获取32位加密算法
	 * 
	 * @param data
	 * @param charset
	 * @return
	 */
	public static String get32MD5(String data, Charset charset) {
		return encrypt(data, charset).toString();
	}

	/**
	 * 开始加密
	 * 
	 * @param data
	 * @param charset
	 * @return
	 */
	private static StringBuffer encrypt(String data, Charset charset) {
		StringBuffer result = null;
		if (data != null) {
			MessageDigest md5; // 调用java内部实现
			try {
				md5 = MessageDigest.getInstance(TYPE);
				md5.update(data.getBytes(charset.getCharset()));
			} catch (Exception e) {
				throw new RuntimeException(e);
			}

			result = toHex(md5.digest()); // 调用加密方法
		}

		return result;
	}

	/**
	 * 开始加密
	 * 
	 * @param bytes
	 * @return
	 */
	private static StringBuffer toHex(byte[] bytes) {
		StringBuffer str = new StringBuffer(32);
		int length = bytes.length;
		for (int i = 0; i < length; ++i) {
			str.append(hexDigits[((bytes[i] & 0xF0) >> 4)]);
			str.append(hexDigits[(bytes[i] & 0xF)]);
		}
		return str;
	}
}